package br.com.intelsys.basics.net;

import org.apache.commons.net.util.SubnetUtils;
import org.springframework.stereotype.Service;

@Service
public class NetService {

	public static String longToIp(long l) {
		return (l >> 24 & 0xFF) + "." + (l >> 16 & 0xFF) + "." + (l >> 8 & 0xFF) + "." + (l & 0xFF);
	}

	public static long ipToLong(String ipAddr) {
		String[] addrArray = ipAddr.split("\\.");
		long num = 0;
		for (int i = 0; i < addrArray.length; i++) {
			int power = 3 - i;
			num += Integer.parseInt(addrArray[i]) % 256 * Math.pow(256, power);
		}
		return num;
	}

	public static boolean isIpInRange(String subnet, String addressTest) {
		String[] subnetArr = subnet.split("/");
		if (subnetArr.length == 2) {
			try {
				return isIpInRange(subnetArr[0], Integer.parseInt(subnetArr[1]), addressTest);
			} catch (NumberFormatException e) {
				return false;
			}
		}
		return false;
	}

	public static boolean isIpInRange(String validAddress, int validMask, String addressTest) {
		return isIpInRange(ipToLong(validAddress), (byte) validMask, addressTest);
	}

	public static boolean isIpInRange(long validAddress, byte validMask, String addressTest) {
		SubnetUtils util = new SubnetUtils(longToIp(validAddress) + "/" + (int) validMask);
		try {
			return util.getInfo().isInRange(addressTest);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return false;
	}
}
